<template>
  <div>
    <van-cell @click="$emit('on-search', item)" v-for="(item, i) in suggestions" :key="i" icon="search">
      <div slot="title" v-html="formatSuggestion(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  data() {
    return {
      suggestions: [],
      id: null
      // str: 'Hello <span style="color: red">World</span>'
    }
  },

  props: {
    searchText: {
      type: String,
      required: true
    }
  },

  watch: {
    searchText: {
      // 监视的数据发生变化触发
      // handler(val) {
      //   clearTimeout(this.id)
      //   this.id = setTimeout(() => {
      //     this.loadSearchSuggestions()
      //   }, 1000)
      // },
      handler: debounce(function (val) {
        this.loadSearchSuggestions()
      }, 1000),
      // 首次监视触发
      immediate: true
    }
  },

  created() {

  },

  methods: {
    // 加载联想建议数据
    async loadSearchSuggestions() {
      try {
        const res = await getSearchSuggestion(this.searchText)
        this.suggestions = res.data.options
      } catch (err) {
        this.$toast('获取失败')
      }
    },
    // 处理suggestions中item的数据
    formatSuggestion(item) {
      // {} new Object()
      // [] new Array()
      // /11/ newRegExp()
      const reg = new RegExp(this.searchText, 'gi')
      const newItem = item.replace(reg, '<span style="color: red">' + this.searchText + '</span>')
      return newItem
    }
  }
}
</script>

<style scoped lang='less'>
</style>
